<template>
  <div class="json-editor" :id="jsonEditorId"></div>
</template>

<script>
  import 'jsoneditor/dist/jsoneditor.css'
  import JSONEditor from 'jsoneditor'

  export default {
    name: "JsonEditor",
    props: ['value', 'jsonEditorId'],
    watch: {
      value: {
        immediate: true,
        handler(val) {
          if (!this.internalChange) {
            this.setEditor(val)
          }
        },
        deep: true
      }
    },
    data() {
      return {
        editor: null,
        json: this.value,
        internalChange: false,
      }
    },
    mounted() {
      let container = document.getElementById(this.jsonEditorId);
      let self = this;

      let options = {
        mode: 'code',
        modes: ['code'],
        onChange() {
          try {
            let json = self.editor.get();
            self.json = json;
            self.$emit('json-change', json);
            self.internalChange = true;
            self.$emit('input', json);
            self.$nextTick(function () {
              self.internalChange = false
            })
          } catch (e) {
            self.$emit('has-error', e);
          }
        }
      };

      this.editor = new JSONEditor(container, options, this.json)
    },
    methods: {
      setEditor(value) {
        if (this.editor) {
          this.editor.set(value)
        }
      }
    }
  }
</script>

<style>
  .json-editor {
    width: 100%;
    height: 100%;
  }

  div.jsoneditor-outer.has-status-bar {
    margin-bottom: -26px !important;
    padding-bottom: 26px !important;
  }
</style>

